package com.lxb.myforum.service

import java.util.*

import com.lxb.myforum.repository.DictionaryRepository
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

import com.lxb.myforum.domain.PageResponse
import com.lxb.myforum.pojo.Dictionary
import com.lxb.myforum.service.spec.DictionarySpec

@Service("dictService")
class DictionaryService @Autowired
constructor(private val dictRepository: DictionaryRepository) {

    fun findAll(dict: Dictionary, pageable: PageRequest): PageResponse<Dictionary> {
        val dicts = dictRepository.findAll(DictionarySpec(dict), pageable)

        return PageResponse(
                code = 200,
                page = dicts.number.toLong(),
                size = dicts.size.toLong(),
                rows = dicts.content,
                totalCount = dicts.totalElements,
                totalPage = dicts.totalPages.toLong()
        )
    }

    fun findByPId(pId: Long): List<Dictionary> {
        return dictRepository.findByParentId(pId)
    }

    @Throws(Throwable::class)
    fun findById(id: Long): Dictionary {
        return dictRepository.findById(id).orElseThrow { RuntimeException("不存在id=" + id + "的model") }
    }

    fun delete(dict: Dictionary): Map<String, Any> {
        val result = HashMap<String, Any>()
        result["action"] = "delete"
        try {
            dictRepository.delete(dict)
            result["result"] = 1
        } catch (e: Exception) {
            result["result"] = -1
            result["errorMsg"] = e.message!!
        }

        return result
    }

    /**
     * 保存字典 （新增或者更新）
     *
     * @param dict
     * @return
     */
    @Transactional
    fun save(dict: Dictionary): Dictionary? {

        if (dict.id == null) { // 说明是新增
            dict.createTime = Date()
            dict.updateTime = Date()

            // 修改父dict的状态
            val pDict = dictRepository.findById(dict.parentId!!)
                    .map {
                        it.isParent = true
                        it.updateTime = Date()
                        return@map it
                    }
                    .orElse(null)

            if (pDict != null) {
                dictRepository.save(pDict)
            }

            return dictRepository.save(dict)
        }

        val tempDict = dictRepository.findById(dict.id!!)
                .map {
                    it.updateTime = Date() // 更新时间一直在变的
                    it.name = dict.name ?: it.name
                    it.dictKey = dict.dictKey ?: it.dictKey
                    it.dictValue = dict.dictValue ?: it.dictValue

                    return@map it
                }
                .orElseThrow { java.lang.RuntimeException("不存在id为"+dict.id+"的model") }

        return dictRepository.save(tempDict)
    }

    @Transactional
    fun deleteById(id: Long): Map<String, Any> {

        val result = HashMap<String, Any>()
        result["action"] = "delete"

        val optionalTempDict = dictRepository.findById(id)

        if (optionalTempDict.isPresent) {
            val (_, _, _, isParent) = optionalTempDict.get()

            // 只会删除该id的Resource和与该Resource相关的联系（如果是多对多，即是第三张表的数据【两者之间的联系】）
            // 并不会删除与该Resource相关连的表的信息
            try {
                if (isParent) {
                    dictRepository.deleteByPId(id)
                }
                dictRepository.deleteById(id)
                result["result"] = 1
            } catch (e: IllegalArgumentException) {
                result["result"] = -1
            }

        } else {
            result["result"] = -1
        }

        return result
    }
}
